/*
 * Copyright (c) 2024 Black Sesame Technologies
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "dal_rticonnextdds/listener_impl/TopicListenerImpl.hpp"
#include "dal_rticonnextdds/entity_impl/DalTopicImpl.hpp"
#include "dal_rticonnextdds/utils/log.hpp"
#include "dal_rticonnextdds/utils/EntityMappingManager.hpp"

TopicListenerImpl::TopicListenerImpl(dal_topic_listener_callbacks_t callbacks)
{
    this->callbacks_ = callbacks;
    this->rti_topic_listener_ = new DDS_TopicListener();
    *(this->rti_topic_listener_) = DDS_TopicListener_INITIALIZER;

    if (this->callbacks_.on_inconsistent_topic) {
        this->rti_topic_listener_->on_inconsistent_topic = TopicListenerImpl::on_inconsistent_topic;
    } else {
        this->rti_topic_listener_->on_inconsistent_topic =
            TopicListenerImpl::on_inconsistent_topic_dummy;
    }

    this->rti_topic_listener_->as_listener.listener_data =
        reinterpret_cast<void*>(&this->callbacks_);
}

TopicListenerImpl::~TopicListenerImpl()
{
    if (this->rti_topic_listener_) {
        delete this->rti_topic_listener_;
        this->rti_topic_listener_ = nullptr;
    }
}

DDS_TopicListener* TopicListenerImpl::getListener()
{
    return this->rti_topic_listener_;
}

void TopicListenerImpl::on_inconsistent_topic(void* listener_data,
                                              DDS_Topic* topic,
                                              const DDS_InconsistentTopicStatus* status)
{
    dal_topic_listener_callbacks_t* callbacks =
        reinterpret_cast<dal_topic_listener_callbacks_t*>(listener_data);
    if (callbacks->on_inconsistent_topic == nullptr)
        return;

    dal_topic_t* dal_topic = EntityMappingGetTopic(topic);
    if (!dal_topic) {
        return;
    }

    dal_inconsistent_topic_status_t dal_status;
    StatusConverter::GetInstance()->ConvertInconsistentTopicStatusFromRtiddsToDal(status,
                                                                                  &dal_status);

    void* data = callbacks->data_;
    (callbacks->on_inconsistent_topic)(dal_topic, &dal_status, data);
}

void TopicListenerImpl::on_inconsistent_topic_dummy(void* listener_data,
                                                    DDS_Topic* topic,
                                                    const DDS_InconsistentTopicStatus* status)
{
}